<template>
	<view>
		<view class="count_box">
			<view class="count_item_box">
				{{ hours }}
			</view>小时
			<view class="count_item_box">
				{{ minutes }}
			</view>分钟
			<view class="count_item_box">
				{{ seconds }}
			</view>秒
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			targetDate: {
				type: String,
				required: true
			}
		},
		data() {
			return {
				countdownInterval: null,
				days: '00',
				hours: '00',
				minutes: '00',
				seconds: '00'
			};
		},
		mounted() {
			this.startCountdown();
		},
		beforeDestroy() {
			cancelAnimationFrame(this.countdownInterval);
		},
		methods: {
			startCountdown() {
				this.updateCountdown(); // 先立即更新一次
				this.countdownInterval = requestAnimationFrame(this.updateCountdown);
			},
			updateCountdown() {
				const now = new Date();
				const target = new Date(this.targetDate);
				const duration = Math.max(0, (target - now) / 1000);

				if (duration <= 0) {
					cancelAnimationFrame(this.countdownInterval);
					this.$emit('countdownFinished'); // 触发倒计时结束事件
					this.resetCountdown();
					return;
				}

				this.days = this.formatTimeUnit(Math.floor(duration / 86400));
				this.hours = this.formatTimeUnit(Math.floor((duration % 86400) / 3600));
				this.minutes = this.formatTimeUnit(Math.floor((duration % 3600) / 60));
				this.seconds = this.formatTimeUnit(Math.floor(duration % 60));

				this.countdownInterval = requestAnimationFrame(this.updateCountdown);
			},
			formatTimeUnit(value) {
				return value < 10 ? '0' + value : value.toString();
			},
			resetCountdown() {
				this.days = '00';
				this.hours = '00';
				this.minutes = '00';
				this.seconds = '00';
			}
		},
		template: `
    <div>
      <span>{{ days }}</span> days 
      <span>{{ hours }}</span> hours 
      <span>{{ minutes }}</span> minutes 
      <span>{{ seconds }}</span> seconds
    </div>
  `
	};
</script>
<style lang="scss">
	.count_box {
		display: flex;
		align-items: center;

		.count_item_box {
			padding: 6rpx 10rpx;
			font-size: 11px;
			border-radius: 10rpx;
			color: #333;
			margin: 0 2rpx;
		}
	}
</style>